// pages/index/index.js
const app = getApp()
const { getBanners, getCategories, getRecommendGoods } = require('../../service/api')

Page({
  data: {
    banners: [],
    categories: [],
    recommendGoods: []
  },

  onLoad() {
    // 初始化数据
    this.initData()
  },

  // 初始化数据
  async initData() {
    try {
      // 并行请求多个接口
      const [bannersRes, categoriesRes, goodsRes] = await Promise.all([
        getBanners(),
        getCategories(),
        getRecommendGoods()
      ])
      
      this.setData({
        banners: bannersRes.data,
        categories: categoriesRes.data,
        recommendGoods: goodsRes.data
      })
    } catch (error) {
      console.error('初始化数据失败', error)
    }
  },

  // 跳转到分类页面
  navigateToCategory(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/category/category?id=${id}`
    })
  },

  // 跳转到商品详情
  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    })
  },

  onPullDownRefresh() {
    // 下拉刷新
    this.initData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    // 上拉加载更多
    console.log('上拉加载更多')
  }
})
